﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using WSIMServices.model;
using System.Data;

namespace WSIMServices
{

    [WebService(Namespace = "http://www.ocdstudio.net/chat")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ChatDB : System.Web.Services.WebService
    {

        WSIMProfilesTableAdapters.wsim_userTableAdapter users;
        WSIMMessagingTableAdapters.wsim_message_modelTableAdapter msgs;
        WSIMCompatibilityTableAdapters.CompatibilityMessageModelTableAdapter compat;

        public ChatDB()
        {
            users = ObjectFactory.GetUserTable();
            msgs = ObjectFactory.GetMessageTable();
            compat = ObjectFactory.GetCompatibleMessageTable();
        }

        [WebMethod]
        public void SendMessage(string user, string pwd, string msg, string rcpt)
        {
            if (!Authenticate(user, pwd)) return;

            lock (msgs)
            {
                long sender, receiver;
                sender = (long)users.GetID(user);
                receiver = (long)users.GetID(rcpt);
                msgs.Insert(DateTime.Now.Ticks, sender, receiver, 1, msg, DateTime.Now, 1, null);
            }

        }

        [WebMethod]
        public bool Authenticate(string user, string pwd)
        {
            try
            {
                new WSIMAuthentication().Validate(user, pwd);
            }
            catch
            {
                return false;
            }
            return true;
        }

        [WebMethod]
        public DataSet GetMessagesMobile(string user, string pwd, string from)
        {
            if (!Authenticate(user, pwd)) return (null);

            DataTable t;
            lock (msgs)
            {
                t = compat.GetDataByRequest(from, user);
                msgs.UpdateReadMessage((long)users.GetID(user));
            }

            DataSet set = new DataSet();
            set.Tables.Add(t);
            return set;

        }



    }
}
